package order

import (
	"errors"
	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
	"go.mongodb.org/mongo-driver/bson"
	"higame/config"
	"higame/modules/log"
	"higame/modules/store"
	"higame/modules/utils"
	log2 "higame/routes/log"
	"higame/routes/user"
)

func handleFH(ctx *gin.Context) error {
	orderId := ctx.PostForm("order_id")
	expressName := ctx.PostForm("express_name")
	expressNumber := ctx.PostForm("express_number")
	// 获取当前登录用户
	claims, err := store.GetClaims(ctx)
	if err != nil {
		log.Error.Println(err)
		return err
	}
	filter := bson.M{
		"order_id": orderId,
	}
	// 只有管理员和卖家才能设置发货状态
	if claims.Audience != config.AdminName {
		filter["seller"] = claims.Audience
	}

	orderItem, err := FindOne(filter)
	if err != nil {
		return errors.New("当前用户权限不足")
	}

	// 只有订单状态为[FK]才能进行此操作
	if orderItem.OrderStatus != FK {
		return errors.New("当前用户权限不足")
	}

	updateDoc := bson.M{
		"order_status": FH,
		"fh_time":      utils.Timestamp(),
	}
	// 判读订单类型来确认是否要求必须输入快递单号
	if orderItem.OrderType == Goods {
		if expressName == "" || expressNumber == "" {
			return errors.New("参数不能为空")
		} else {
			updateDoc["express_type"] = Express{
				Name:   expressName,
				Number: expressNumber,
			}
		}
	}

	// 修改订单
	return UpdateOneByOrderID(orderId, updateDoc)
}

func handleSH(ctx *gin.Context) error {
	orderId := ctx.PostForm("order_id")
	// 获取当前登录用户
	claims, err := store.GetClaims(ctx)
	if err != nil {
		log.Error.Println(err)
		return err
	}
	filter := bson.M{
		"order_id": orderId,
	}

	// 只有管理员和买家才能设置发货状态
	if claims.Audience != config.AdminName {
		filter["buyer"] = claims.Audience
	}

	orderItem, err := FindOne(filter)
	if err != nil {
		return errors.New("当前用户权限不足")
	}

	// 只有订单状态为[FH]才能进行此操作
	if orderItem.OrderStatus != FH {
		return errors.New("当前用户权限不足")
	}

	updateDoc := bson.M{
		"order_status": SH,
		"sh_time":      utils.Timestamp(),
	}

	// 修改订单
	if err := UpdateOneByOrderID(orderId, updateDoc); err != nil {
		return err
	}

	// 打款给卖方
	seller := orderItem.Seller
	if orderItem.Seller == config.AdminNick {
		seller = config.AdminName
	}
	integral := int64(orderItem.Price) * orderItem.Quantity
	if err := user.UpdateOne(bson.M{"username": seller}, bson.M{
		"$inc": bson.M{
			"integral": integral,
		},
	}); err != nil {
		return err
	}
	// 记录卖方进账日志

	return log2.AddOneIntegralLog(&log2.IntegralLogSchema{
		UUID:     uuid.NewV1().String(),
		AddTime:  utils.Timestamp(),
		Username: seller,
		Integral: integral,
		Text:     "交易进账",
		Other:    utils.JoinString("%v x %v", orderItem.Title, orderItem.Quantity),
	})
}

func handleQX(ctx *gin.Context) error {
	orderId := ctx.PostForm("order_id")
	// 获取当前登录用户
	claims, err := store.GetClaims(ctx)
	if err != nil {
		log.Error.Println(err)
		return err
	}
	filter := bson.M{
		"order_id": orderId,
	}

	// 只有管理员、买方、卖家都能取消订单
	if claims.Audience != config.AdminName {
		filter["$or"] = bson.A{
			bson.M{
				"seller": claims.Audience,
			},
			bson.M{
				"buyer": claims.Audience,
			},
		}
	}

	orderItem, err := FindOne(filter)
	if err != nil {
		return errors.New("当前用户权限不足")
	}

	// 只有订单状态为[FK]才能进行此操作
	if orderItem.OrderStatus != FK {
		return errors.New("当前用户权限不足")
	}

	updateDoc := bson.M{
		"order_status": QX,
		"qx_time":      utils.Timestamp(),
	}

	// 修改订单
	if err := UpdateOneByOrderID(orderId, updateDoc); err != nil {
		return err
	}

	// 退款给买方
	integral := int64(orderItem.Price) * orderItem.Quantity
	if err := user.UpdateOne(bson.M{
		"username": orderItem.Buyer,
	}, bson.M{
		"$inc": bson.M{
			"integral": integral,
		},
	}); err != nil {
		return err
	}

	// 库存复原
	if err := RestoreQuantity(orderItem.OrderType, orderItem.GoodsID, orderItem.Quantity); err != nil {
		return err
	}

	// 记录卖方进账日志
	return log2.AddOneIntegralLog(&log2.IntegralLogSchema{
		UUID:     uuid.NewV1().String(),
		AddTime:  utils.Timestamp(),
		Username: orderItem.Buyer,
		Integral: integral,
		Text:     "交易退款",
		Other:    utils.JoinString("%v X %v", orderItem.Title, orderItem.Quantity),
	})
}
